#include "tcp_client.h"

TCPClient::TCPClient()
{
    //初始化TCP客户端
    tcpClient = new QTcpSocket(this);   //实例化tcpClient
    tcpClient->abort();                 //取消原有连接
    // read data
    connect(tcpClient, SIGNAL(readyRead()), this, SLOT(ReadData()));
    // err
    connect(tcpClient, SIGNAL(error(QAbstractSocket::SocketError)), \
            this, SLOT(ReadError(QAbstractSocket::SocketError)));

    tcpClient->connectToHost("127.0.0.1", 899);//ui->edtIP->text(), ui->edtPort->text().toInt());
    if (tcpClient->waitForConnected(1000))  // 连接成功则进入if{}
    {
        // ui->btnConnect->setText("断开");
        // ui->btnSend->setEnabled(true);
    }
}

void TCPClient::ReadData()
{
    QByteArray buffer = tcpClient->readAll();
    if(!buffer.isEmpty())
    {
        // ui->edtRecv->append(buffer);
    }
}

void TCPClient::WriteData()
{
    QString data = "Hello Server"; //ui->edtSend->toPlainText();
    if(data != "")
    {
        tcpClient->write(data.toLatin1()); //qt5去除了.toAscii()
    }
}


void TCPClient::ReadError(QAbstractSocket::SocketError)
{
    tcpClient->disconnectFromHost();
    // ui->btnConnect->setText(tr("连接"));
    // QMessageBox msgBox;
    // msgBox.setText(tr("failed to connect server because %1").arg(tcpClient->errorString()));
xec();
}
